if (process.env.VUE_APP_MOCK_ENABLE === 'true') {
  let Mock = require('../public/static/js/mock');
  let configArr = [];
  // 路径参数转化为对象
  const params2Object = function(url) {
    const search = url.split('?')[1];
    if (!search) {
      return {};
    }
    return JSON.parse(
      '{"' + 
        decodeURIComponent(search)
          .replace(/"/g, '\\"')
          .replace(/&/g, '","')
          .replace(/=/g, '":"')
          .replace(/\+/g, ' ') +
      '"}'
    );
  }
  // 规整响应（普通对象、函数返回(可以接收axios的传参到参数e中)）
  function XHR2ExpressReqWarp(respond) {
    return function(options) {
      // options为axios请求的传参，包括type、url、body(为post请求方式的data传参)
      let result = null;
      if (respond instanceof Function) {
        const { type, url } = options;
        let { body } = options;
        // 先按JSON字符串来转对象
        // 若出错，则按URL来转对象，若还是出错，则传递原参数值
        try {
          body = JSON.parse(body);
        } catch (e) {
          try {
            body = params2Object('?' + body);
          } catch (err) {
            window.console.error('Mocks XHR2ExpressReqWarp request data fromat error.');
            return;
          }
        }
        result = respond({
          method: type,
          body,
          query: params2Object(url)
        });
      } else {
        result = respond;
      }
      return Mock.mock(result);
    }
  }
  Mock.setup({
    timeout: '300-1000'
  });
  const files = require.context('./api', true, /\.js$/);
  files.keys().map(path => {
    configArr = configArr.concat(files(path).default);
  });
  for (const mock of configArr) {
    // 打印有哪些 mock api
    console.log('-' + mock.type + '- ' + mock.url);
    // 注册 mockjs
    Mock.mock(new RegExp(mock.url), mock.type || 'get', XHR2ExpressReqWarp(mock.response));
  }
}
